package com.example.demo.BookService.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.BookService.impl.BookWithUserService;
import com.example.demo.entity.BookWithUser;
import com.example.demo.mapper.BookWithUserMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BookWithUserServiceImpl implements BookWithUserService {

    @Resource
    BookWithUserMapper bookWithUserMapper;

    /**
     * 将图书添加到借阅中
     * @param bookWithUser
     */
    public void insert(BookWithUser bookWithUser) {
        bookWithUserMapper.insert(bookWithUser);
    }

    /**
     * 续借书籍
     * @param bookWithUser
     */
    public void update(BookWithUser bookWithUser) {
        UpdateWrapper<BookWithUser> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("isbn", bookWithUser.getIsbn()).eq("id", bookWithUser.getId());
        bookWithUserMapper.update(bookWithUser, updateWrapper);
    }

    /**
     * 删除一条借阅记录
     * @param bookWithUser
     */
    public void deleteRecord(BookWithUser bookWithUser) {
        Map<String, Object> map = new HashMap<>();
        map.put("isbn", bookWithUser.getIsbn());
        map.put("id", bookWithUser.getId());
        bookWithUserMapper.deleteByMap(map);
    }

    /**
     * 批量删除借阅记录
     * @param bookWithUsers
     */
    public void deleteRecords(List<BookWithUser> bookWithUsers) {
        int len = bookWithUsers.size();
        for (int i = 0; i < len; i++) {
            BookWithUser curRecord = bookWithUsers.get(i);
            Map<String, Object> map = new HashMap<>();
            map.put("isbn", curRecord.getIsbn());
            map.put("id", curRecord.getId());
            bookWithUserMapper.deleteByMap(map);
        }
    }

    /**
     * 分页查询借阅记录
     * @param pageNum
     * @param pageSize
     * @param search1
     * @param search2
     * @param search3
     * @return
     */
    public Page<BookWithUser> selectPage(Integer pageNum, Integer pageSize, String search1, String search2, String search3) {
        LambdaQueryWrapper<BookWithUser> wrappers = Wrappers.<BookWithUser>lambdaQuery();
        if (StringUtils.isNotBlank(search1)) {
            wrappers.like(BookWithUser::getIsbn, search1);
        }
        if (StringUtils.isNotBlank(search2)) {
            wrappers.like(BookWithUser::getBookName, search2);
        }
        if (StringUtils.isNotBlank(search3)) {
            wrappers.like(BookWithUser::getId, search3);
        }
        Page<BookWithUser> BookPage = bookWithUserMapper.selectPage(new Page<>(pageNum, pageSize), wrappers);
        return BookPage;
    }
}
